import type { SpaceApi } from '#/api/core/space';
import type { AppApi } from '#/api/core/app';

import { ref } from 'vue';

import { defineStore } from 'pinia';

import { getSpaceList, getSpaceDetail } from '#/api/core/space';
import { getAppList, getAppDetail } from '#/api/core/app';

export const useTableForgeStore = defineStore('tableforge', () => {
  // 当前选中的空间、应用ID
  const currentSpaceId = ref<string>('');
  const currentAppId = ref<string>('');

  // 空间列表
  const spaceList = ref<SpaceApi.Space[]>([]);
  // 应用列表
  const appList = ref<AppApi.App[]>([]);

  // 加载状态
  const loadingSpace = ref(false);
  const loadingApp = ref(false);

  // 获取所有空间
  async function fetchSpaceList() {
    try {
      loadingSpace.value = true;
      const result = await getSpaceList();
      spaceList.value = result || [];
      return spaceList.value;
    } finally {
      loadingSpace.value = false;
    }
  }

  // 获取空间详情
  async function fetchSpaceDetail(id: string) {
    if (!id) return null;
    try {
      loadingSpace.value = true;
      return await getSpaceDetail(id);
    } finally {
      loadingSpace.value = false;
    }
  }

  // 获取空间下的所有应用
  async function fetchAppList(spaceId: string) {
    if (!spaceId) return [];
    try {
      loadingApp.value = true;
      const result = await getAppList(spaceId);
      appList.value = result || [];
      return appList.value;
    } finally {
      loadingApp.value = false;
    }
  }

  // 获取应用详情
  async function fetchAppDetail(id: string) {
    if (!id) return null;
    try {
      loadingApp.value = true;
      return await getAppDetail(id);
    } finally {
      loadingApp.value = false;
    }
  }

  // 设置当前选中的空间
  function setCurrentSpace(id: string) {
    currentSpaceId.value = id;
  }

  // 设置当前选中的应用
  function setCurrentApp(id: string) {
    currentAppId.value = id;
  }

  return {
    currentSpaceId,
    currentAppId,
    spaceList,
    appList,
    loadingSpace,
    loadingApp,
    fetchSpaceList,
    fetchSpaceDetail,
    fetchAppList,
    fetchAppDetail,
    setCurrentSpace,
    setCurrentApp,
  };
});
